<template>
  <div class="goods-manager">
    <div class="manager-header">
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">
        新增商品
      </el-button>
      <el-button @click="refreshList" icon="el-icon-refresh">
        刷新
      </el-button>
    </div>

    <div class="goods-grid">
      <div 
        v-for="goods in goodsList" 
        :key="goods.id"
        class="goods-card"
        :class="{ 'selected': selectedGoods.includes(goods.id) }"
        @click="toggleSelect(goods)"
      >
        <div class="goods-image">
          <image-preview :src="goods.image" :width="160" :height="120"/>
          <div class="goods-overlay">
            <el-button 
              type="primary" 
              size="mini" 
              icon="el-icon-edit"
              @click.stop="handleEdit(goods)"
            >
              编辑
            </el-button>
          </div>
        </div>
        <div class="goods-info">
          <h4>{{ goods.name }}</h4>
          <div class="goods-price">¥{{ goods.price }}</div>
          <p>{{ goods.link }}</p>
          <div class="goods-status">
            <el-tag :type="goods.status === 1 ? 'success' : 'info'">
              {{ goods.status === 1 ? '已上架' : '已下架' }}
            </el-tag>
          </div>
        </div>
        <div class="select-indicator">
          <i class="el-icon-check" v-if="selectedGoods.includes(goods.id)"></i>
        </div>
      </div>
    </div>

    <div class="manager-footer">
      <div class="selected-info">
        已选择 {{ selectedGoods.length }} 个商品
      </div>
      <div class="actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确认选择
        </el-button>
      </div>
    </div>

    <!-- 商品编辑弹窗 -->
    <el-dialog 
      :title="editMode === 'add' ? '新增商品' : '编辑商品'" 
      :visible.sync="editDialogVisible"
      width="600px"
    >
      <el-form 
        ref="goodsForm" 
        :model="goodsForm" 
        :rules="goodsRules" 
        label-width="100px"
      >
        <el-form-item label="商品图片" prop="image">
          <image-upload v-model="goodsForm.image" />
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="goodsForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="goodsForm.price" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="详情链接" prop="link">
          <el-input v-model="goodsForm.link" placeholder="请输入商品详情链接" />
        </el-form-item>
        <el-form-item label="所属校区" prop="campusId" v-if="isAdmin">
          <el-select v-model="goodsForm.campusId" placeholder="请选择校区" style="width: 100%">
            <el-option
              v-for="campus in campusList"
              :key="campus.campusId || campus.id"
              :label="campus.campusName || campus.name"
              :value="campus.campusId || campus.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属校区" v-else>
          <el-input :value="getCurrentCampusName()" disabled />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="goodsForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, addGoods, updateGoods } from '@/api/home/goods/goods'

export default {
  name: 'GoodsManager',
  props: {
    selected: {
      type: Array,
      default: () => []
    },
    currentCampusId: {
      type: Number,
      default: null
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    campusList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      goodsList: [],
      selectedGoods: [],
      editDialogVisible: false,
      editMode: 'add',
      goodsForm: {
        id: null,
        image: '',
        name: '',
        price: '',
        link: '',
        status: 1,
        campusId: null
      },
      goodsRules: {
        image: [
          { required: true, message: '请上传商品图片', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        link: [
          { required: true, message: '请输入详情链接', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    console.log('GoodsManager mounted - props:', {
      currentCampusId: this.currentCampusId,
      isAdmin: this.isAdmin,
      campusListLength: this.campusList.length,
      campusList: this.campusList
    })
    this.loadGoodsList()
    this.initializeSelected()
  },
  watch: {
    selected: {
      handler() {
        this.initializeSelected()
      },
      immediate: true
    },
    campusList: {
      handler(newVal) {
        console.log('GoodsManager campusList changed:', newVal)
      },
      immediate: true
    }
  },
  methods: {
    // 初始化已选择项
    initializeSelected() {
      if (this.selected && this.selected.length > 0) {
        this.selectedGoods = this.selected.map(item => 
          typeof item === 'object' ? item.id : item
        )
      } else {
        this.selectedGoods = []
      }
    },

    // 加载商品列表
    async loadGoodsList() {
      try {
        const query = { status: 1 } // 只显示已上架的
        
        // 如果不是超级管理员，添加校区筛选
        if (!this.isAdmin && this.currentCampusId) {
          query.campusId = this.currentCampusId
        }
        
        const response = await listGoods(query)
        this.goodsList = response.rows || []
      } catch (error) {
        this.$message.error('加载商品列表失败')
      }
    },

    // 切换选择状态
    toggleSelect(goods) {
      const index = this.selectedGoods.indexOf(goods.id)
      if (index > -1) {
        this.selectedGoods.splice(index, 1)
      } else {
        this.selectedGoods.push(goods.id)
      }
    },

    // 新增商品
    handleAdd() {
      this.editMode = 'add'
      this.resetForm()
      this.editDialogVisible = true
    },

    // 重置表单
    resetForm() {
      this.goodsForm = {
        id: null,
        image: '',
        name: '',
        price: '',
        link: '',
        status: 1,
        campusId: this.isAdmin ? null : this.currentCampusId
      }
    },

    // 获取当前校区名称
    getCurrentCampusName() {
      if (!this.currentCampusId) {
        return '超级管理员'
      }
      const campus = this.campusList.find(c => 
        (c.campusId || c.id) === this.currentCampusId
      )
      return campus ? (campus.campusName || campus.name) : '未知校区'
    },

    // 编辑商品
    handleEdit(goods) {
      this.editMode = 'edit'
      this.goodsForm = { ...goods }
      this.editDialogVisible = true
    },

    // 保存商品
    async handleSave() {
      this.$refs.goodsForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.editMode === 'add') {
              await addGoods(this.goodsForm)
              this.$message.success('新增成功')
            } else {
              await updateGoods(this.goodsForm)
              this.$message.success('更新成功')
            }
            
            this.editDialogVisible = false
            this.loadGoodsList()
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.goodsForm = {
        id: null,
        image: '',
        name: '',
        price: '',
        link: '',
        status: 1
      }
    },

    // 刷新列表
    refreshList() {
      this.loadGoodsList()
    },

    // 取消选择
    handleCancel() {
      this.$emit('close')
    },

    // 确认选择
    handleConfirm() {
      const selectedGoodsData = this.goodsList.filter(goods => 
        this.selectedGoods.includes(goods.id)
      )
      this.$emit('select', selectedGoodsData)
    }
  }
}
</script>

<style scoped>
.goods-manager {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.goods-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  overflow-y: auto;
  padding: 10px 0;
}

.goods-card {
  position: relative;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.goods-card:hover {
  border-color: #1976d2;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15);
}

.goods-card.selected {
  border-color: #1976d2;
  background-color: #e3f2fd;
}

.goods-image {
  position: relative;
  height: 120px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.goods-image >>> .el-image {
  width: 100%;
  height: 100%;
}

.goods-image >>> .el-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.goods-card:hover .goods-overlay {
  opacity: 1;
}

.goods-info {
  padding: 15px;
}

.goods-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  font-size: 16px;
  color: #ff4757;
  font-weight: bold;
  margin-bottom: 8px;
}

.goods-info p {
  margin: 0 0 10px 0;
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-status {
  display: flex;
  justify-content: flex-end;
}

.select-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #1976d2;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.goods-card.selected .select-indicator {
  opacity: 1;
}

.manager-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 10px;
}
</style> 